var express = require('express');
var mysql      = require('mysql');

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'test'
});
 
connection.connect();
 
connection.query('select version() as ver;', function (error, results, fields) {
  if (error) throw error;
  console.log('mysql version: ', results[0].ver);
});

var app = express();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
 
app.use(express.static('www'));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.get('/', function (req, res) {
  res.redirect("index.html");
});

app.get('/result', upload.array(), function (req, res, next) {
  //console.log(req.query);
  //res.json(req.body);
  connection.query("select count(*) as c from `cross` where `lng` = ? and `lat` = ?",
    [req.query.lng,req.query.lat],
    function (error, results, fields) {
      if(error)
        res.send({existed:false});
      else if(results[0].c>0)
        res.send({existed:true,count:results[0].c});
      else
        res.send({existed:false});
    });
});

app.post('/result', upload.array(), function (req, res, next) {
  //console.log(req.body);
  //res.json(req.body);
  connection.query("INSERT INTO `cross` (`lng`,`lat`,`road1`) VALUES (?,?,?);",
    [req.body.lng,req.body.lat,req.body.street],
    function (error, results, fields) {
    if(error)
      res.send({insert:false});
    else
      res.send({insert:true});
  });
});

var server = app.listen(8080, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("server start at http://%s:%s", host, port)
})